package xyz.eden.cloud.common.core.io.file;

import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;

@NoArgsConstructor
public class FileUtils extends org.apache.commons.io.FileUtils {

    private static final PosixFilePermission[] WRITE_PERMISSIONS = {PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_WRITE};

    public static void append(String appendValue, File file) throws Exception {
        createParentDirectory(file);
        if (file.exists()) {
            assertCanOverwrite(file);
        }
        try (FileWriter writer = new FileWriter(file)) {
            writer.append(appendValue);
        }
    }

    private static void assertCanOverwrite(File file) throws IOException {
        if (!file.canWrite() || !canWriteFile(file)) {
            throw new FileNotFoundException(file.getPath() + "permission denied");
        }
    }

    private static boolean canWriteFile(File file) throws IOException {
        try {
            Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file.toPath());
            for (PosixFilePermission permission : WRITE_PERMISSIONS) {
                if (permissions.contains(permission)) {
                    return true;
                }
            }
            return false;
        } catch (UnsupportedOperationException ex) {
            // Assume that we can
            return true;
        }
    }


    private static void createParentDirectory(File file) {
        File parent = file.getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }
    }
}
